<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once(APPPATH.'controllers/admin/abstractAdmin.php');
class User extends Abstractadmin
{
    public function  __construct()
    {
        parent::__construct();
        $this->load->model("usermodel");
        $this->load->model("pointmodel");
        $this->load->model("userplacemodel");
        $this->load->model("placemodel");
        $this->isAdmin();
    }


    public function  addedit()
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }
        $data['host']=$host;
        $id=$this->input->get("id",true);
        $user_type=$host['type'];
        if($id){
            $data['user']=$this->usermodel->getById($id);
            $rs = $this->userplacemodel->getByUid($id);
            $pid = [];

            foreach ($rs as $row) {
               array_push($pid,$row['pid']); 
            }
            $data['pid'] = $pid;
        }else{
            $data['addflag']=true;
        }
        $res= $this->placemodel->listmap();
        $data['places'] = $res;
        $this->load->view("admin/add_edit", $data);
    }


    public  function  saveOrUpdate()
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }


        $id=$this->input->post("id",true);
        $pid = $this->input->post('place',true);
        $username=$this->input->post("username",true);
        $type=$this->input->post("user_type",true);
        $password=$this->input->post("password",true);

        //todo check parameters and auth
        if(!$id&&$this->usermodel->getByUsername($username))
        {
            self::json(array("code"=>"0",'msg'=>"此用户名已存在,请更换用户名!"));
        }

        $insert=array(
            "username"=>$username,
            "type"=>$type,
            "c_time"=>time(),
            "password"=>$password
        );

        if($id && $pid || $id)
        {
            $insert_array = array();
            for ($i = 0; $i < count($pid); $i++) {
                array_push($insert_array, array('pid' => $pid[$i],'uid' => $id, 'c_time' => time()));
            }
            $result=$this->usermodel->update($insert,$id);
            $rs = $this->userplacemodel->updateBatch($insert_array,'pid');
            if($result && $rs)
            {
               self::json(array('code' => '1', 'msg' => '更新用户成功'));
            }
            else
            {
                self::json(array('code' => '0', 'msg' => '更新用户失败，请联系管理员！'));
            }
        }
        else
        {
            $result=$this->usermodel->insert($insert);
            if($result)
            {
                $fresh = $this->usermodel->getByUsername($username);
                $id = $fresh['id'];
                $insert_array = array();
                for ($i = 0; $i < count($pid); $i++) {
                    array_push($insert_array, array('pid' => $pid[$i],'uid' => $id, 'c_time' => time()));
                }

                $rs = $this->userplacemodel->updateBatch($insert_array,'pid');
                if ($rs) {
                   self::json(array('code' => '1', 'msg' => '添加用户成功！'));
                }
                else {
                   self::json(array('code' => '0', 'msg' => '添加用户失败，请联系管理员！'));    
                }
            }
            else
            {
                self::json(array('code' => '0', 'msg' => '添加用户失败，请联系管理员！'));
            }
        }


    }

    public function delete()
    {
          $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }

        $id=$this->input->post("uid",true);
        $result=$this->usermodel->delete($id);
        if($result){
                self::json(array('code' => '1', 'msg' => '删除用户成功！'));
        }else{
                self::json(array('code' => '0', 'msg' => '删除用户失败！'));
        }
    }

    public function  index($page=1)
    {
        $host=$this->getUser();

        if(!$page||$page<1)
        {
            $page=1;
        }

        $pagesize=10;
        $user_type=$host['type'];
        $where="  ";
        $data['where']=$where;
        $data['page']=$page;
        $data['pagesize']=$pagesize;
        $data['host']=$host;
        $list=$this->usermodel->listUserByCondition($where,$page,$pagesize);
        $total=$this->usermodel->countByCondition($where);
        $lastPg=intval(($total/$pagesize))+($total%$pagesize==0?0:1);
        $data['lastpg']=$lastPg;
        $data['total']=$total;
        $data['list']=$list;

        $this->load->view("admin/index",$data);
    }


    public function profile()
    {
        $host=$this->getUser();
        $user_id=$host['id'];
        $user=$this->usermodel->getById($user_id);
        $data['user']=$user;
        $data['host']=$host;
        $this->load->view("/admin/userProfile",$data);
    }

    public function pwd(){
        $host=$this->getUser();
        $user_id=$host['id'];
        $user=$this->usermodel->getById($user_id);
        $data['user']=$user;
        $data['host']=$host;
        $this->load->view("/admin/userPwd",$data);
    }

    public  function  editUserPwd(){
        $host=$this->getUser();
        $user_id=$host['id'];
        $data['host']=$host;

        $id=$this->input->get("id",true);
        if($id){
            $user=$this->usermodel->getById($id);
            $data['user']=$user;
            $this->load->view("/admin/user_userPwd",$data);
        }else{
            $data['msg']="参数错误";
            $data['code']=0;
            $this->load->view("/admin/user_error",$data);
            return ;
        }
    }

    public function updateUserPwd(){
        $host=$this->getUser();
       

        $id=$this->input->post("id",true);
        $pwd=$this->input->post("pwd",true);
        $pwd2=$this->input->post("pwd2",true);
        if(!$id||$pwd!=$pwd2){
            self::json(array('code' => '0', 'msg' => '参数错误！'));
        }

        $data['password']=$pwd;
        $re=$this->usermodel->update($data, $id);
        $re = 1;
        if($re){
            self::json(array('code' => '1', 'msg' => '更新密码成功!'));
        }else{
            self::json(array('code' => '0', 'msg' => '更新密码失败！'));
        }
    }

    public function updateProfile()
    {
        $host=$this->getUser();
        $name=$this->input->post("name",true);

        $data['id']=$host['id'];
        $data['name']=$name;
        $re=$this->usermodel->update($data,$host['id']);
        if($re){
                self::json(array('code' => '1', 'msg' => '更新资料成功！'));
        }else{
                self::json(array('code' => '0', 'msg' => '更新资料失败！'));
        }
    }

    public function updatePwd(){
        $host=$this->getUser();
        $user=$this->usermodel->getById($host['id']);
        $oldpwd=$this->input->post("oldpwd",true);
        $pwd=$this->input->post("pwd",true);
        $pwd2=$this->input->post("pwd2",true);
        if($user['password']!=$oldpwd||$pwd!=$pwd2){
             self::json(array('code' => '0', 'msg' => '参数错误！'));
        }

        $data['password']=$pwd;

        $re=$this->usermodel->update($data,$host['id']);
        if($re){
                self::json(array('code' => '1', 'msg' => '更新密码成功！'));
        }else{
                self::json(array('code' => '0', 'msg' => '更新密码失败！'));
        }
    }

     public function  addProject()
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }
        $data['host']=$host;
        $id=$this->input->get("id",true);
        $user_type=$host['type'];
        if($id){
            $data['user']=$user=$this->pointmodel->getById($id);
            $province = $data['user']['province'];
        }else{
            $data['addflag']=true;
        }
        $this->load->view("admin/add_project",$data);
    }

    public function  places($page=1)
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }

        if(!$page||$page<1)
        {
            $page=1;
        }

        $pagesize=10;
        $user_type=$host['type'];
        $where="  ";
        $data['where']=$where;
        $data['page']=$page;
        $data['pagesize']=$pagesize;
        $data['host']=$host;
        $list=$this->placemodel->listPlaceByCondition($where,$page,$pagesize);

	/*foreach($list as &$l){
		$l['province']=iconv( "GBK","UTF-8", $l['province']); 
	}*/

        $total=$this->placemodel->countByCondition($where);
        $lastPg=intval(($total/$pagesize))+($total%$pagesize==0?0:1);
        $data['lastpg']=$lastPg;
        $data['total']=$total;
        $data['list']=$list;

        $this->load->view("admin/places",$data);
    }

    public  function addeditPlace() {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }

        $data['host']=$host;
        $id=$this->input->get("id",true);
        $user_type=$host['type'];
        if($id){
            $data['place']=$this->placemodel->getById($id);
            $data['point']=$this->pointmodel->getByPid($id);
        }else{
            $data['addflag']=true;
        }

        $this->load->view("admin/addeditPlace", $data);    
    }

    public  function  saveOrUpdatePlace()
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }


        $id=$this->input->post("id",true);
        $pid = $this->input->post('pid',true);
        $name = $this->input->post("name",true);
        $province = $this->input->post("province",true);


        //todo check parameters and auth
        if(!$id&&$this->placemodel->getByPlaceName($name))
        {
            self::json(array("code"=>"0",'msg'=>"该监测区域名称已存在，请更换名称！"));
        }

        $insert =  array(
            'province' => $province,
            'name' => $name,
            "c_time" => time(),
        );
        if($id)
        {
            $result=$this->placemodel->update($insert,$id);
            //$rs = $this->placemodel->update($insert1,$pid);
            if($result)
            {
               self::json(array('code' => '1', 'msg' => '更新监测区域成功'));
            }
            else
            {
                self::json(array('code' => '0', 'msg' => '更新监测区域失败，请联系管理员！'));
            }

        }
        else
        {
            $result=$this->placemodel->insert($insert);
            //$rs=$this->placemodel->insert($insert1);
            if($result)
            {   
                $rs = $this->placemodel->getByProvinceName($province);
                $id = $rs['id'];
                self::json(array('code' => '1', 'msg' => '添加监测区域成功！', 'id' => ''.$id));
            }
            else
            {
                self::json(array('code' => '0', 'msg' => '添加监测区域失败，请联系管理员！'));
            }
        }


    }

    public function deletePlace()
    {
        $host=$this->getUser();
          
        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }

        $id=$this->input->post("uid",true);
        $result=$this->placemodel->delete($id);
        if($result){
                self::json(array('code' => '1', 'msg' => '删除地点成功！'));
        }else{
                self::json(array('code' => '0', 'msg' => '删除地点失败！'));
        }
    }

    public function fetchPlaceData()
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }

        $result = $this->placemodel->listmap();

       if ($result) {
            self::json(array('code' => 1, 'data' => $result));
        }
        
    }

    public  function  saveOrUpdatePoint()
    {
        $host=$this->getUser();

        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }


        $id=$this->input->post("id",true);
        $pid = $this->input->post('pid',true);
        $name = $this->input->post("name",true);
        $phone = $this->input->post("phone",true);


        //todo check parameters and auth
        if(!$id&&$this->pointmodel->getByPointName($name))
        {
            self::json(array("code"=>"0",'msg'=>"该监测点名称已存在，请更换名称！"));
        }

        if(!$pid)
        {
            self::json(array("code"=>"0",'msg'=>"监测区域不存在，请检查监测区域"));
        }

        $insert =  array(
            'pid' => $pid,
            'phone' => $phone,
            'name' => $name,
            "c_time" => time(),
        );
        if($id && $pid)
        {
            $result=$this->pointmodel->update($insert,$id);
            if($result)
            {
               self::json(array('code' => '1', 'msg' => '更新监测点成功'));
            }
            else
            {
                self::json(array('code' => '0', 'msg' => '更新监测点失败，请联系管理员！'));
            }
        }
        else
        {
            $result=$this->pointmodel->insert($insert);
            if($result)
            {
                self::json(array('code' => '1', 'msg' => '添加监测点成功！'));
            }
            else
            {
                self::json(array('code' => '0', 'msg' => '添加监测点失败，请联系管理员！'));
            }
        }


    }

     public function deletePoint()
    {
        $host=$this->getUser();
          
        if($host['type']!=USER_TYPE_ADMIN){
            exit("authority error");
        }

        $id=$this->input->post("id",true);
        $result=$this->pointmodel->delete($id);
        if($result){
                self::json(array('code' => '1', 'msg' => '删除监测点成功！'));
        }else{
                self::json(array('code' => '0', 'msg' => '删除监测点失败！'));
        }
    }
}
